//编辑器
var editor;
$(function () {
    // 编辑器初始化
    editor = new FroalaEditor('#editor',
        ({
            placeholderText: '',
            charCounterCount: true,//默认 显示字数
            saveInterval: 0,//不自动保存，默认10000，0为不自动保存
            toolbarBottom: false,//默认
            toolbarInline: false,//true选中设置样式,默认false
            imageUploadMethod: 'POST',
            heightMin: 300,
            charCounterMax: 3000,  //最大字数限制，-1为不限制
            // saveURL: '/NewsController/addNotify',  //自动保存的地址（body参数为html内容）
            saveURL: '/knowledgeSection/addKnSection',  //自动保存的地址（body参数为html内容）

            saveParams: {postId: '1'},  //保存内容时传的参数
            spellcheck: false,  //是否允许浏览器对输入内容进行拼写检查
            imageUploadURL: '/file/uploadByOneFileEdit',//上传到本地服务器
            videoUploadURL: '/file/uploadByOneFileEdit',
            imageDefaultWidth: 1300,
            imageResizeWithPercent: true,
            autoHeightEnabled:true,
            language: 'zh_cn',

        }));
    $('select').selectpicker();

    let customerId_data='';


    $("#customerId").on('shown.bs.select',function(e) {

        if(customerId_data==''){

            let send_data='<option value="">加载中。。。</option>'
            $("#customerId").html(send_data);
            $('#customerId').selectpicker('refresh');
            setTimeout(function () {
                $.ajax({
                    type: 'POST',
                    dataType: "json",
                    url: '/customerController/getCustomerList',
                    cache : false,
                    data:{
                    },
                    async : false,
                    success: (function (data) {
                        if (data.code == "000000") {
                            //<option value="">请选择</option>
                            var html = '';
                            $.each(data.data, function(n, value) {
                                html += "<option value=" + value.customerId + ">" +  value.customerName + "</option>";
                            });
                            customerId_data=html
                            $("#customerId").html(html);
                            // $('#customerId').selectpicker('refresh')

                            $("#customerId").html(html).selectpicker('refresh').on('changed.bs.select', function (e, clickedIndex, isSelected, previousValue) {      // 内容变更触发
                                if($('.form-horizontal').data('bootstrapValidator')!=undefined){
                                    $('.form-horizontal').data('bootstrapValidator')
                                        .updateStatus('customerId', 'NOT_VALIDATED',null)
                                        .validateField('customerId');
                                }
                            });



                        } else {
                            alert("请求失败");
                        }
                    }),
                    error: (function (res) {
                        alert("请求失败");
                    })
                });
            },100)

        }else{
            $("#customerId").html(customerId_data);
            // $('#customerId').selectpicker('refresh')

            $("#customerId").html(customerId_data).selectpicker('refresh').on('changed.bs.select', function (e, clickedIndex, isSelected, previousValue) {      // 内容变更触发
                if($('.form-horizontal').data('bootstrapValidator')!=undefined){
                    $('.form-horizontal').data('bootstrapValidator')
                        .updateStatus('customerId', 'NOT_VALIDATED',null)
                        .validateField('customerId');
                }
            });
        }


    })
});



/**
 * 提交工单
 */
function saveWorkOrder() {

    var workOrderTitle = $('#workOrderTitle').val(); //工单标题
    var workOrderType = $('#workOrderType').val(); //工单类型
    var workOrderContent= $('#editor .fr-view').html();  //工单内容
    let customerId=$("#customerId").val()



    //联系人姓名为空判断
    var contactNameReg = /^[\u4e00-\u9fa5A-Za-z0-9_-]+[\)）（，；\(\.\%。\u4e00-\u9fa5A-Za-z0-9_-]?$/;
    var pattern = new RegExp(contactNameReg);
    $('.form-horizontal').bootstrapValidator({
        fields: {
            workOrderTitle: {
                validators: {
                    notEmpty: {
                        message: '标题不能为空'
                    },
                    regexp: {
                        regexp: /^[\u4e00-\u9fa5A-Za-z0-9_-]+[\)）（，；\(\.\%。\u4e00-\u9fa5A-Za-z0-9_-]?$/,
                        message: '请输入正确的标题'
                    }
                }
            },
            workOrderType: {
                validators: {
                    notEmpty: {
                        message: '类型不能为空'
                    }
                }
            },
            customerId: {
                validators: {
                    notEmpty: {
                        message: '客户名称不能为空'
                    }
                }
            },

        },
    })
    $(".form-horizontal").bootstrapValidator('validate');//提交验证
    if (!$(".form-horizontal").data('bootstrapValidator').isValid()) {//获取验证结果，如果成功，执行下面代码

        return;
    }
    // if(!workOrderTitle){
    //     promptInfo("工单标题不能为空！");
    //     return;
    // }else{
    //     if(!pattern.test(workOrderTitle)) {
    //         promptInfo("请输入正确的工单标题");
    //         return;
    //     }
    // }
    //
    // //联系类型
    // if(!workOrderType){
    //     promptInfo("工单类型不能为空！");
    //     return;
    // }

    var jsonDatan = {
        logName: workOrderTitle,
        logType : workOrderType,
        logContent : workOrderContent,
        customerId:customerId
    }


    $.ajax({
        url: '/workLog/addWorkLog',
        type: 'POST',
        dataType: "json",
        contentType: "application/json;charset=utf-8",
        data: JSON.stringify(jsonDatan),
        success: (function (data) {
            if (data.code == "000000") {
                // $.alert("操作成功！");
                $.alert({
                    title:'提示',
                    content:"创建成功",
                    buttons:{
                        confirm:{
                            text: "确认",
                            btnClass: 'btn-primary',
                            action:function () {
                                var $thisTabs = parent.$('.mt-nav-bar .nav-tabs').find('li.active');
                                var navTab = parent.$multitabs._getNavTab($thisTabs);
                                closeTab(navTab);
                                if(location.search=='?bs=0'){
                                    //管理端
                                    openTab("工作日志","/front/manage/manageWorkLogList");
                                    refreshActivePane("/front/manage/manageWorkLogList");
                                }else if(location.search=='?bs=1'){
                                    //用户端
                                    openTab("工作日志","/front/user/userWorkLogList");
                                    refreshActivePane("/front/user/userWorkLogList");
                                }else if(location.search.indexOf('?bs=1s')==0){
                                    // (str.indexOf('|') == -1)
                                    //    用户端客户详情 customerDetailUser
                                    let url = "/front/user/customerManager/customerDetail?customerId="+location.search.split('=')[2]
                                    openTab("客户详情", url);
                                    let customerIframe = $(window.parent.document).find('iframe[src="' + url + '"]')[0];
                                    customerIframe.contentWindow.refreshTable("userWorkList");

                                }else if(location.search.indexOf('?bs=0s')==0){
                                    // (str.indexOf('|') == -1)
                                    //    管理端客户详情
                                    let url = "/front/customerManager/customerDetail?customerId="+location.search.split('=')[2]
                                    openTab("客户详情", url);
                                    let customerIframe = $(window.parent.document).find('iframe[src="' + url + '"]')[0];
                                    customerIframe.contentWindow.refreshTable("userWorkList");

                                }


                                delStorageAndRemove(navTab);
                            }
                        }
                    }
                })

            } else {
                alert("操作失败");
            }
        }),
        error: (function () {
            alert("失败");
        })
    });
}




function cancelAddWorkOrder(){
    window.location.reload();
}

/**
 * 消息提示弹出框
 * @param content  ---提示内容
 */
function promptInfo(content) {
    $.alert({
        title: '温馨提示',
        content: content,
        buttons: {
            confirm: {
                text: '确认',
                btnClass: 'btn-primary'
            }
        }
    });
}

//富文本框的事件
function show_element(e) {
    if($('#editor .fr-view').html()!=''){

        // $(".redvalidators").hide()
        // $("#sureSubmit").attr("disabled",false)
    }
}